package com.yjt.sousou.main;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yjt.sousou.Api;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseFragment;
import com.yjt.sousou.base.PagingBean;
import com.yjt.sousou.create.entity.Finish;
import com.yjt.sousou.detail.OrderDetailActivity;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.http.JsonCallback;
import com.yjt.sousou.main.entity.OrderFilterBean;
import com.yjt.sousou.main.entity.OrderListEntity;
import com.yjt.sousou.main.entity.OrderListFilterBean;
import com.yjt.sousou.main.entity.RefreshData;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.HDPreference;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL;


/**
 * 作者：83734
 * 时间：2018/11/21
 * 描述：首页工单列表
 */
public class OrderFragment extends BaseFragment implements
        SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener,
        OrderListAdapter.ReceiveOrderListener, OrderListAdapter.OnItemClickListener {
    @BindView(R.id.rv_home)
    RecyclerView mRecyclerView;
    @BindView(R.id.srl_index)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.ll_main)
    LinearLayout mLlMain;
    @BindView(R.id.rv_filter)
    RecyclerView mRvFilter;
    private OrderListAdapter mAdapter;
    private boolean isRefresh = true;
    private PagingBean BEAN = new PagingBean();
    private PopupWindow mPop;
    private String startTime = "";
    private String endTime = "";
    private String areaId = "";
    private String placeId = "";
    private String department = "";
    private String userId = "";
    private String listType = "";
    private String zhuangtai = "未修好";
    private String isParts = "";
    private int mFrom;

    @Override
    protected Object setLayoutId() {
        return R.layout.fragment_order;
    }

    public static OrderFragment newInstance(int from) {
        OrderFragment newestFragment = new OrderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("from", from);
        newestFragment.setArguments(bundle);
        return newestFragment;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initRefreshLayout();
        initRecyclerView();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void refresh() {
        isRefresh = true;
        BEAN.setPageIndex(1);
        mRefreshLayout.setRefreshing(true);
        startTime = "";
        endTime = "";
        areaId = "";
        placeId = "";
        department = "";
        initData();
    }

    @Subscribe
    public void handleSomethingElse(OrderFilterBean event) {
        if (mFrom == event.getFrom()) {
            BEAN.setPageIndex(1);
            mRefreshLayout.setRefreshing(true);
            startTime = event.getTimeStart();
            endTime = event.getTimeOver();
            areaId = event.getAreaId();
            placeId = event.getPlaceId();
            department = event.getDepartmentId();
            isParts = event.getIsParts();
            initData();
        }
    }

    @Subscribe
    public void refreshData(RefreshData refreshData) {
        refresh();
    }

    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
        mFrom = getArguments().getInt("from");
        if(TextUtils.isEmpty(userId)){
            userId = HDPreference.getUserId(LoginTag.USER_ID.name());
        }
        if(mFrom == 0){
            setOrderFilterView(getMyOrderFilterList());
        }
        if (mFrom == 2) {
            listType = "";
            setOrderFilterView(getOrderFilterList());
        }
        if (mFrom == 1) {
            listType = "";
        }
        initData();
    }

    private List<OrderListFilterBean> getMyOrderFilterList(){
        List<OrderListFilterBean> list = new ArrayList<>();
        list.add(new OrderListFilterBean("未修好",true));
        list.add(new OrderListFilterBean("已修好",false));
        return list;
    }
    private List<OrderListFilterBean> getOrderFilterList(){
        List<OrderListFilterBean> list = new ArrayList<>();
        list.add(new OrderListFilterBean("全部",true));
        list.add(new OrderListFilterBean("未派修",false));
        list.add(new OrderListFilterBean("维修中",false));
        list.add(new OrderListFilterBean("待评价",false));
        list.add(new OrderListFilterBean("已完成",false));
        return list;
    }
    /**
     * mFrom==0 zhuangtai      传值中文   已修好  未修好
     * mFrom==2 list_type  1、未派修 2、维修中 3、待评价 4、已完成
     */
    private void setOrderFilterView(List<OrderListFilterBean> list) {
        mRvFilter.setLayoutManager(new LinearLayoutManager(getActivityContext(),HORIZONTAL,false));
        BaseQuickAdapter<OrderListFilterBean, BaseViewHolder> adapter = new BaseQuickAdapter<OrderListFilterBean, BaseViewHolder>
                (R.layout.item_order_list_filter,list) {
            @Override
            protected void convert(BaseViewHolder helper, OrderListFilterBean item) {
                TextView tvName = helper.getView(R.id.tv_filter_item);
                tvName.setText(item.name);
                if(item.isClicked){
                    tvName.setBackgroundResource(R.drawable.rectangle_blue);
                    tvName.setTextColor(ContextCompat.getColor(getActivityContext(),R.color.white));
                }else {
                    tvName.setBackgroundResource(R.drawable.rectangle_blue_hollow);
                    tvName.setTextColor(ContextCompat.getColor(getActivityContext(),R.color.black));
                }
            }
        };

        adapter.setOnItemClickListener((adapter1, view, position) -> {
            List<OrderListFilterBean> data = adapter.getData();
            for (int i = 0; i < data.size(); i++) {
                data.get(i).isClicked = i == position;
            }
            isRefresh = true;
            BEAN.setPageIndex(1);
            if(mFrom == 0){
                zhuangtai = position==0?"未修好":"已修好";
            }else {
                listType = String.valueOf(position);
            }
            initData();
            adapter1.notifyDataSetChanged();
        });
        mRvFilter.setAdapter(adapter);
    }

    private void initData() {
        if(mRefreshLayout!=null){
            mRefreshLayout.setRefreshing(true);
        }
        OkGo.<OrderListEntity>get(Api.get().getOrderList())
                .tag(this)
                .params("datastart", startTime)
                .params("dataover", endTime)
                .params("page", BEAN.getPageIndex())
                .params("pagesize", BEAN.getPageSize())
                .params("select_quyu", areaId)
                .params("select_didian", placeId)
                .params("select_bumen", department)
                .params("user_id", userId)
                .params("list_type", listType)
                .params("zhuangtai", mFrom==0?zhuangtai:"")
                //1.我的接单 2 待接单 3 报修列表（全部） 4.我的报修
                .params("type", mFrom + 1)
                .params("is_pj", isParts)
                .execute(new JsonCallback<OrderListEntity>(OrderListEntity.class) {
                    @Override
                    public void onSuccess(Response<OrderListEntity> response) {
                        OrderListEntity entity = response.body();
                        mRefreshLayout.setRefreshing(false);
                        if ("0".equals(entity.getReturncode())) {
                            if (entity.getData() != null && entity.getData().size() > 0) {
                                setData(entity.getData());
                            } else {
                                setData(new ArrayList());
                                showToast("没有数据");
                            }
                        } else {
                            if (isRefresh && BEAN.getPageIndex() == 1) {
                                setData(new ArrayList());
                            }
                            showToast("没有数据");
                        }
                    }
                });
    }

    private void initRecyclerView() {
        final LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new OrderListAdapter(R.layout.item_order_list, new ArrayList<OrderListEntity.DataBean>());
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
        mAdapter.setReceiveOrderListener(this);
        mAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(OrderListEntity.DataBean item) {
        Intent intent = new Intent(getActivityContext(), OrderDetailActivity.class);
        intent.putExtra("orderId", item.getId());
        startActivity(intent);
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode == Constant.ORDER_FINISH && resultCode == RESULT_OK){
//            refresh();
//        }
//    }

    private void initRefreshLayout() {
        mRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light
        );
        mRefreshLayout.setProgressViewOffset(true, 120, 300);
        mRefreshLayout.setRefreshing(true);
        mRefreshLayout.setOnRefreshListener(this);
    }

    private void setData(List data) {
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < BEAN.getPageSize()) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        BEAN.setPageIndex(1);
        initData();
    }

    @Override
    public void onLoadMoreRequested() {
        isRefresh = false;
        BEAN.addIndex();
        initData();
    }

    //接单
    @Override
    public void clicked(OrderListEntity.DataBean item) {
        showReceivePop(item);
        makeWindowDark();
    }

    //接单
    private void showReceivePop(final OrderListEntity.DataBean item) {
        View view = LayoutInflater.from(getActivityContext()).inflate(R.layout.pop_receive_order, null);
        TextView tv_receive = view.findViewById(R.id.tv_receive);
        TextView tv_ignore = view.findViewById(R.id.tv_ignore);
        TextView tv_pop_title = view.findViewById(R.id.tv_pop_title);
        tv_pop_title.setText("待接工单");
        TextView tv_num = view.findViewById(R.id.tv_num);
        tv_num.setText(item.getOrderid());
        TextView tv_name = view.findViewById(R.id.tv_name);
        tv_name.setText(item.getBaoxiu());
        TextView tv_location = view.findViewById(R.id.tv_location);
        tv_location.setText(item.getQuyu());
        TextView tv_des = view.findViewById(R.id.tv_des);
        tv_des.setText(item.getYuanyin());
        ImageView tv_close = view.findViewById(R.id.tv_close);
        mPop = new PopupWindow(view, 4 * mScreenWidth / 5, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(mLlMain, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_receive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiveOrder(item.getId());
            }
        });
        tv_ignore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
    }

    //接单
    private void receiveOrder(String orderId) {
        OkGo.<Finish>post(Api.get().getOrderReceive())
                .tag(this)
                .params("user_id", userId)
                .params("id", orderId)
                .execute(new DialogCallback<Finish>(Finish.class, getActivityContext()) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish finish = response.body();
                        if (finish.getReturncode().equals("0")) {
                            showToast("接单成功");
                            if (mPop != null) {
                                mPop.dismiss();
                            }
                            isRefresh = true;
                            BEAN.setPageIndex(1);
                            EventBus.getDefault().post(new RefreshData(0));
                        }
                    }
                });
    }

}
